package com.fbt.transfer.app.driver.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermissionUtils {
  private static final String TAG = "PermissionUtils";
  private static final String PREF_NAME = "permission_pref";
  private static final String KEY_PERMISSION_REQUESTED = "permission_requested";
  private static final String KEY_OVERLAY_PERMISSION_REQUESTED = "overlay_permission_requested";

  // 权限请求码
  private static final int PERMISSION_REQUEST_CODE = 100;
  private static final int MANAGE_STORAGE_REQUEST_CODE = 101;

  // 需要请求的基本权限列表（不包括悬浮窗权限）
  private static final String[] REQUIRED_PERMISSIONS = {
    // Manifest.permission.ACCESS_FINE_LOCATION,    // GPS权限
    Manifest.permission.READ_PHONE_STATE, // 读取设备状态权限
    Manifest.permission.POST_NOTIFICATIONS, // 通知权限
    Manifest.permission.READ_EXTERNAL_STORAGE, // 读取存储权限
    Manifest.permission.WRITE_EXTERNAL_STORAGE // 写入存储权限
  };
  public static Map<String, String> permissionMap =
      new HashMap<>() {
        {
          put(Manifest.permission.READ_PHONE_STATE, "• 设备状态权限：用于读取设备信息");
          put(Manifest.permission.POST_NOTIFICATIONS, "• 通知权限：用于发送重要通知");
          put(Manifest.permission.READ_EXTERNAL_STORAGE, "• 存储权限：用于保存应用数据");
        }
      };

  private static SharedPreferences getPrefs(Context context) {
    return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
  }

  public static int getPermissionRequestCode() {
    return PERMISSION_REQUEST_CODE;
  }

  public static int getManageStorageRequestCode() {
    return MANAGE_STORAGE_REQUEST_CODE;
  }

  /** 检查是否已经请求过权限 */
  public static boolean hasRequestedPermissions(Context context) {
    return getPrefs(context).getBoolean(KEY_PERMISSION_REQUESTED, false);
  }

  /** 检查是否已经请求过悬浮窗权限 */
  public static boolean hasRequestedOverlayPermission(Context context) {
    return getPrefs(context).getBoolean(KEY_OVERLAY_PERMISSION_REQUESTED, false);
  }

  /** 标记已请求过权限 */
  public static void markPermissionsRequested(Context context) {
    getPrefs(context).edit().putBoolean(KEY_PERMISSION_REQUESTED, true).apply();
  }

  /** 标记已请求过悬浮窗权限 */
  public static void markOverlayPermissionRequested(Context context) {
    getPrefs(context).edit().putBoolean(KEY_OVERLAY_PERMISSION_REQUESTED, true).apply();
  }

  /** 检查所有必需权限是否已授予 */
  public static boolean checkAllPermissions(Context context) {
    List<String> missingPermissions = getMissingPermissions(context);
    return missingPermissions.isEmpty();
  }

  /** 获取未授予的权限列表 */
  public static List<String> getMissingPermissions(Context context) {
    List<String> missingPermissions = new ArrayList<>();

    // 检查基本权限
    for (String permission : REQUIRED_PERMISSIONS) {
      if (ContextCompat.checkSelfPermission(context, permission)
          != PackageManager.PERMISSION_GRANTED) {
        missingPermissions.add(permission);
      }
    }

    return missingPermissions;
  }

  /** 检查存储权限是否已授予 */
  public static boolean hasStoragePermission(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
      return Environment.isExternalStorageManager();
    } else {
      boolean readPermission =
          ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
              == PackageManager.PERMISSION_GRANTED;
      boolean writePermission =
          ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
              == PackageManager.PERMISSION_GRANTED;
      return readPermission && writePermission;
    }
  }

  /** 请求存储权限 */
  public static void requestStoragePermission(Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
      try {
        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse(String.format("package:%s", activity.getPackageName())));
        activity.startActivityForResult(intent, MANAGE_STORAGE_REQUEST_CODE);
      } catch (Exception e) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
        activity.startActivityForResult(intent, MANAGE_STORAGE_REQUEST_CODE);
      }
    } else {
      ActivityCompat.requestPermissions(
          activity,
          new String[] {
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
          },
          MANAGE_STORAGE_REQUEST_CODE);
    }
  }

  /** 请求所有必需的权限 */
  public static void requestAllPermissions(Activity activity) {
    List<String> missingPermissions = getMissingPermissions(activity);

    if (!missingPermissions.isEmpty()) {
      // 请求基本权限
      ActivityCompat.requestPermissions(
          activity, missingPermissions.toArray(new String[0]), PERMISSION_REQUEST_CODE);
      markPermissionsRequested(activity);
    }
  }

  /** 检查悬浮窗权限是否已授予 */
  public static boolean hasOverlayPermission(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      return Settings.canDrawOverlays(context);
    }
    return true;
  }

  /** 请求悬浮窗权限 */
  public static void requestOverlayPermission(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      Intent intent =
          new Intent(
              Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
              Uri.parse("package:" + context.getPackageName()));
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(intent);
      markOverlayPermissionRequested(context);
    }
  }

  /** 检查特定权限是否已授予 */
  public static boolean checkPermission(Context context, String permission) {
    return ContextCompat.checkSelfPermission(context, permission)
        == PackageManager.PERMISSION_GRANTED;
  }

  /** 请求特定权限 */
  public static void requestPermission(Activity activity, String permission, int requestCode) {
    if (!checkPermission(activity, permission)) {
      ActivityCompat.requestPermissions(activity, new String[] {permission}, requestCode);
    }
  }
}
